package com.sso.web.controller;

import com.sso.comm.cons.Const;
import com.sso.comm.cons.ParamConst;
import com.sso.comm.cookie.TokenHelper;
import com.sso.comm.domain.Ticket;
import com.sso.comm.domain.Token;
import com.sso.comm.encrypt.AES;
import com.sso.comm.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @createTime: 2016/10/19 10:57
 */
@Controller
@RequestMapping("sso")
public class SsoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(SsoController.class);

    /**
     * 登录界面
     *
     * @param mav
     * @return
     */
    @RequestMapping("/login.htm")
    public ModelAndView login(ModelAndView mav, HttpServletRequest request) {
        String retUlr = request.getParameter(Const.ReturnURL);
        request.getSession().setAttribute(Const.ReturnURL, HttpUtil.encodeURL(retUlr));
        mav.setViewName("/login");
        return mav;
    }

    /**
     * 检查登录
     *
     * @return
     */
    @RequestMapping(value = "/checklogin.htm")
    public String checklogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        Ticket tic = (Ticket) request.getSession().getAttribute(Const.Data);
        if ("admin".equals(name) && "admin".equals(password)) {
            Token token = new Token(request, ParamConst.cookie_domain);
            token.setId(111l);
            TokenHelper.setSSOCookie(request, response, ParamConst.cookie_domain, token, AES.getInstance());
//            SessionUtils.setAttr(request,Const.cookieName,TokenHelper.encryptCookie(request,token,AES.getInstance()));
            LOGGER.info("web-session-id:" + request.getRequestedSessionId());
            String url = (String) request.getSession().getAttribute(Const.ReturnURL);
            // 跨域
            if (tic != null) {
                tic.setTk(token);
                // 加上sso系统私钥，生成信任签名
                tic.sign(ParamConst.RSA_SSO_Private_key);
                LOGGER.info("login succ!!|重定向到原页面|" + HttpUtil.decodeURL(url) + "?data=" + tic.encryptToken());
                return redirectTo(HttpUtil.decodeURL(url) + "?data=" + tic.encryptToken());
            }
            // 同域
            LOGGER.info("login succ!!|重定向到原页面|" + HttpUtil.decodeURL(url));
            return redirectTo(HttpUtil.decodeURL(url));
        }
        return "login";
    }

    /**
     * 跨域登录
     *
     * @return
     */
    @RequestMapping("/crosslogin.htm")
    public String checkToken(HttpServletRequest request, HttpServletResponse response) {
        String retUlr = request.getParameter(Const.ReturnURL);
        request.getSession().setAttribute(Const.ReturnURL, HttpUtil.encodeURL(retUlr));
        String data = request.getParameter("data");
        // 验证签名
        Ticket tic = verify(request, data);
        if (tic == null) {
            return "/illegal";
        } else {
            // 验证token
            Token token = TokenHelper.getToken(request);
            if (token == null) {
                return "/sso/login" + "?data=" + tic.encryptToken();
            }
            tic.setTk(token);
            // 加上sso系统私钥，生成信任签名
            tic.sign(ParamConst.RSA_SSO_Private_key);
            LOGGER.info("login succ!!|重定向到原页面|" + HttpUtil.decodeURL(retUlr) + "?data=" + tic.encryptToken());
            return redirectTo(HttpUtil.decodeURL(retUlr) + "?data=" + tic.encryptToken());
        }
    }

    public Ticket verify(HttpServletRequest request, String data) {
        Ticket tic = TokenHelper.replyCiphertext(request, data);
        request.getSession().setAttribute(Const.Data, tic);
        // 验证秘钥签名
        return tic.verify(ParamConst.RSA_OA_Public_key);

    }


    /**
     * 页面跳转url
     *
     * @param url
     * @return
     */
    protected String redirectTo(String url) {
        if (StringUtils.isBlank(url)) {
            return "/succ";
        }
        StringBuffer rto = new StringBuffer("redirect:");
        rto.append(url);
        return rto.toString();
    }
}
